import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useStockStore } from './stock'
import { useProductStore } from './product'

function formatDate(date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

export const useDashboardStore = defineStore('dashboard', () => {
  const stockStore = useStockStore()
  const productStore = useProductStore()

  const initialized = ref(false)

  const ensureInitialized = () => {
    if (!initialized.value) {
      if (!Array.isArray(stockStore.stockList) || stockStore.stockList.length === 0) {
        stockStore.initializeStock()
      }
      if (!Array.isArray(productStore.productList) || productStore.productList.length === 0) {
        productStore.initializeProducts()
      }
      initialized.value = true
    }
  }

  // 销售（出库）按天聚合
  const salesByDate = computed(() => {
    const result = new Map()
    const priceMap = new Map(stockStore.stockList.map(item => [item.id, item.salePrice || 0]))

    stockStore.stockHistory
      .filter(h => h && h.type === 'outbound')
      .forEach(h => {
        const day = formatDate(new Date(h.date))
        const salePrice = priceMap.get(h.productId) || 0
        const amount = (h.quantity || 0) * salePrice
        if (!result.has(day)) {
          result.set(day, { orders: 0, quantity: 0, amount: 0 })
        }
        const agg = result.get(day)
        agg.orders += 1
        agg.quantity += (h.quantity || 0)
        agg.amount += amount
      })

    return result
  })

  // 近 N 天销售额序列
  const buildDailySeries = (days = 7) => {
    const labels = []
    const values = []
    const now = new Date()
    for (let i = days - 1; i >= 0; i--) {
      const d = new Date(now)
      d.setDate(now.getDate() - i)
      const key = formatDate(d)
      labels.push(key.slice(5)) // MM-DD
      const agg = salesByDate.value.get(key)
      values.push(agg ? Number(agg.amount.toFixed(2)) : 0)
    }
    return { labels, values }
  }

  // 今日 KPI
  const getTodayKpis = () => {
    const todayKey = formatDate(new Date())
    const todayAgg = salesByDate.value.get(todayKey) || { orders: 0, quantity: 0, amount: 0 }
    // 使用设置中的全局低库存阈值（如未设置则按各商品 minStock 判定）
    const globalThreshold = Number(localStorage.getItem('low_stock_threshold'))
    let lowStock = 0
    if (!Number.isNaN(globalThreshold)) {
      lowStock = stockStore.stockList.filter(item => item.quantity > 0 && item.quantity <= Math.max(globalThreshold, item.minStock || 0)).length
    } else {
      lowStock = stockStore.getWarningProducts().length
    }
    const aov = todayAgg.orders > 0 ? todayAgg.amount / todayAgg.orders : 0
    return {
      todaySales: Number(todayAgg.amount.toFixed(2)),
      todaySalesWow: 0, // 需要后端或缓存对比，这里先保留 0
      orderCount: todayAgg.orders,
      conversion: 0, // 暂无访客数据
      aov: Number(aov.toFixed(2)),
      aovWow: 0,
      lowStock,
    }
  }

  // Top 商品（按销售数量）
  const getTopProducts = (topN = 10) => {
    const qtyMap = new Map()
    const itemMap = new Map(stockStore.stockList.map(i => [i.id, i]))

    stockStore.stockHistory
      .filter(h => h && h.type === 'outbound')
      .forEach(h => {
        const key = h.productId
        const item = itemMap.get(key)
        if (!item) return
        const prev = qtyMap.get(key) || { code: item.code, name: item.name, quantity: 0, sales: 0, margin: 0 }
        const saleAmount = (h.quantity || 0) * (item.salePrice || 0)
        const profit = (item.salePrice || 0) - (item.costPrice || 0)
        const margin = item.salePrice ? Math.round((profit / item.salePrice) * 100) : 0
        qtyMap.set(key, {
          code: item.code,
          name: item.name,
          quantity: prev.quantity + (h.quantity || 0),
          sales: prev.sales + saleAmount,
          margin,
        })
      })

    return Array.from(qtyMap.values())
      .sort((a, b) => b.quantity - a.quantity)
      .slice(0, topN)
  }

  // 支付方式占比（示例占位）
  const getPaymentBreakdown = () => {
    // 无支付方式数据时，给出稳定的占位结构，便于前端展示
    return [
      { label: '微信', value: 48 },
      { label: '支付宝', value: 32 },
      { label: '现金', value: 15 },
      { label: '银行卡', value: 5 },
    ]
  }

  return {
    // state
    initialized,

    // lifecycle helpers
    ensureInitialized,

    // getters/actions
    buildDailySeries,
    getTodayKpis,
    getTopProducts,
    getPaymentBreakdown,
  }
})


